from sqlalchemy import Column, String, DateTime, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from datetime import datetime
import uuid

from db.base import Base


class DocumentComplianceRelation(Base):
    """文档与合规检查项关联模型 - 实现文档与检查项的双向关联"""
    __tablename__ = "document_compliance_relation"

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    document_id = Column(UUID(as_uuid=True), ForeignKey("personal_document.id", ondelete="CASCADE"), nullable=False, comment="文档ID")
    compliance_template_item_id = Column(UUID(as_uuid=True), ForeignKey("template_item.id", ondelete="CASCADE"), nullable=False, comment="合规检查项ID")
    relation_type = Column(String(50), default="reference", comment="关联类型: reference(参考), evidence(证据), template(模板)")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")

    # 关系定义
    document = relationship("PersonalDocument", back_populates="compliance_relations")
    compliance_template_item = relationship("TemplateItem", back_populates="document_compliance_relations")

    def __repr__(self):
        return f"<DocumentComplianceRelation(document_id={self.document_id}, compliance_template_item_id={self.compliance_template_item_id}, type='{self.relation_type}')>"
